package com.yang.drawcard.base;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.Target;
import com.core.app.Latte;
import com.core.initbase.InitActivity;
import com.core.utils.dbtutil.DbtLog;
import com.core.utils.exit.ExitAppUtils;
import com.yang.drawcard.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by ywm on 2018/8/23.
 */

public class BaseActivity extends InitActivity {

    private final static String TAG = "BaseActivity";

    // 再点一次退出程序时间设置
    public static final long WAIT_TIME = 2000L;
    public long TOUCH_TIME = 0;

    //是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected boolean useThemestatusBarColor = false;
    //是否使用状态栏文字和图标为暗色，如果状态栏采用了白色系，则需要使状态栏和图标为暗色，android6.0以上可以设置
    protected boolean useStatusBarColor = true;


    protected static final int LOCKMESSAGEID = 13;

    private long lockTaskDelay = 100 * 60 * 1000;// 锁屏时间 100分钟
    //private long lockTaskDelay = 10 * 1000;//锁屏时间

    protected static Timer lockTimer = new Timer();
    protected static LockTask lockTask;
    public static boolean isTimeToLock = false;

    final class LockTask extends TimerTask {
        @Override
        public void run() {
            Log.i(TAG, "time down show dialog lock");
            Log.d(TAG,"time down show dialog lock");
            handler.sendEmptyMessage(LOCKMESSAGEID);
        }
    }

    MyHandler handler;

    /**
     * 接收子线程消息的 Handler
     */
    public static class MyHandler extends Handler {

        // 软引用
        SoftReference<BaseActivity> fragmentRef;

        public MyHandler(BaseActivity fragment) {
            fragmentRef = new SoftReference<BaseActivity>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            BaseActivity fragment = fragmentRef.get();
            if (fragment == null) {
                return;
            }

            // 处理UI 变化
            switch (msg.what) {
                case LOCKMESSAGEID:
                    Log.d(TAG,"isTimeToLock = true");
                    isTimeToLock = true;
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        Log.d(TAG,"onCreate");
        ExitAppUtils.getInstance().createActivity(this);
        lockTask = new LockTask();
        handler = new MyHandler(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"onResume");
        unLockScreen();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG,"onPause");
        lockScreen();// 把之前的锁销毁,创建新锁
        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            View currentFocus = this.getCurrentFocus();
            if (currentFocus != null) {
                IBinder windowToken = currentFocus.getWindowToken();
                imm.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        lockTask.cancel();
        //lockTimer.cancel();
        super.onDestroy();
        Log.d(TAG,"onDestroy");
        ExitAppUtils.getInstance().destroyActivity(this);
    }

    public void unLockScreen() {
        Log.d(TAG,"unLockScreen");
        if (isTimeToLock) {
            isTimeToLock = false;
            Log.d(TAG,"isTimeToLock");

            /*LockScreenFragment lockScreenFragment = new LockScreenFragment();
            Bundle thing = new Bundle();
            lockScreenFragment.setArguments(thing);
            extraTransaction().startDontHideSelf(lockScreenFragment);
            Toast.makeText(Latte.getApplicationContext(), "请输入您的账户密码", Toast.LENGTH_SHORT).show();*/


            // Toast.makeText(Latte.getApplicationContext(), "请输入您的账户密码", Toast.LENGTH_SHORT).show();
            // 退出系统
            DbtLog.logUtils(TAG, "退出系统");
            ExitAppUtils.getInstance().exit();
        }
        Log.d(TAG,"cancel isTimeToLock");
        lockTask.cancel();
        lockTimer.cancel();
        Log.i(TAG, "unlockScreen  将原任务从队列中移除");

    }

    public void lockScreen() {

        if (lockTask != null) {
            Log.i(TAG, "lockScreen 将原任务从队列中移除");
            lockTask.cancel(); //将原任务从队列中移除
        }
        Log.i(TAG, "lockScreen");
        lockTask = new LockTask();
        lockTimer = new Timer();
        lockTimer.schedule(lockTask, lockTaskDelay);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG,"onStop");
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device

        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        // 正在运行的程序
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName) && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    /**
     * 判断程序是否在前台运行
     *
     * @param packageName
     * @return
     */
    public boolean isOpen(String packageName) {
        Log.d(TAG,"isOpen");
        if (packageName.equals("") | packageName == null)
            return false;
        ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();
        for (RunningAppProcessInfo runinfo : runningAppProcesses) {
            String pn = runinfo.processName;
            if (pn.equals(packageName) && runinfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
                return true;
        }
        return false;
    }



    //----↓ 长按保存照片 ↓------------------------------------------------------------------------------------------
    public void downPicDate(final String picurl) {
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
            builder.setTitle("保存图片");
            builder.setMessage("是否保存该图片？");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // LatteLoader.showLoading(LoginActivity.this, true);
                    download(picurl);
                }
            });
            builder.setNegativeButton("取消", null).create().show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 保存图片到手机
    public void download(final String url) {

        new AsyncTask<Void, Integer, File>() {

            @Override
            protected File doInBackground(Void... params) {
                File file = null;
                File destFile = null;
                try {
                    FutureTarget<File> future = Glide
                            .with(BaseActivity.this)
                            .load(url)
                            .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);

                    file = future.get();

                    // 首先保存图片 pictureFolder =  "/storage/emulated/0/Pictures"
                    //File pictureFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();

                    // 本地文件路径  appDir =  "/storage/emulated/0/Pictures/Beauty"
                    // File appDir = new File(pictureFolder ,"Beauty");
                    // File appDir = new File(EaseImageUtils.getPicPath(BaseActivity.this));
                    File appDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/Camera/");// /storage/emulated/0/DCIM/Camera
                    if (!appDir.exists()) {
                        appDir.mkdirs();
                    }
                    // String fileName = System.currentTimeMillis() + ".jpg";
                    String fileName = url.substring(url.lastIndexOf("/") + 1);
                    // destFile =  "/storage/emulated/0/Pictures/Beauty/1551859435100.jpg"
                    destFile = new File(appDir, fileName);

                    // 复制文件
                    copy(file, destFile);

                    // 最后通知图库更新
                    BaseActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(destFile.getPath()))));


                } catch (Exception e) {
                    // Log.e("EasePagerViewImageActivity", e.toString());
                }
                // return file;
                return destFile;
            }

            @Override
            protected void onPostExecute(File file) {

                // Toast.makeText(BaseActivity.this, "保存成功路径:" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                Toast.makeText(BaseActivity.this, "图片已保存到相册", Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
            }
        }.execute();
    }

    /**
     * 复制文件
     *
     * @param source 输入文件
     * @param target 输出文件
     */
    public static void copy(File source, File target) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(source);
            fileOutputStream = new FileOutputStream(target);
            byte[] buffer = new byte[1024];
            while (fileInputStream.read(buffer) > 0) {
                fileOutputStream.write(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //----↑ 长按保存照片 ↑--------------------------------------------------------------------------------------------------------------------



    // 沉浸式
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                getWindow().setStatusBarColor(getResources().getColor(R.color.transparent));//设置状态栏背景色
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);//透明
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        } else {
            Toast.makeText(this, "低于4.4的android系统版本不存在沉浸式状态栏", Toast.LENGTH_SHORT).show();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && useStatusBarColor) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    public void reStartApp(){
        Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(Latte.getApplicationContext().getPackageName());
        LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //启动Activity来重启应用程序
        startActivity(LaunchIntent);
        // 关闭所有Activity
        ExitAppUtils.getInstance().exitOnlyLogin();
    }

}
